/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.gui;

import app.gui.scene.SceneHolder;
import app.gui.scene.SceneObserver;
import app.model.HistoryCell;
import app.model.PlayerDataModel;
import app.model.TableBet;
import com.app.ThreadManager;
import com.app.factories.BetFactory;
import com.app.factories.impl.DozenBetFactory;
import com.app.factories.impl.InsideBetFactory;
import com.app.factories.impl.OutsideBetFactory;
import com.app.game.bet.Bet;
import com.app.game.chat.Message;
import com.app.game.other.Credit;
import com.app.game.other.Player;
import com.app.game.other.PlayerFix;
import com.app.observers.PlayerObserver;
import com.app.observers.ServerObserver;
import com.app.task.Task;

import glass.mat.Main;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.LinearGradient;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;

/**
 * 
 * @author sammael
 */
public class Game extends SceneHolder implements ServerObserver,PlayerObserver {

	//private SceneHolder prevHolder;
	private Player player;
	private StackPane sp;
	private String waitingString = "Oczekawianie na pozostałych graczy";
	private String roundDone = "Wylosowano liczbę";
	private Node gameoverBox, roundBox, menuBox;
	private HashMap<Integer, PlayerDataModel> playersData = new HashMap<>();
	private ArrayList<PlayerDataModel> playermodelList = new ArrayList<>();
	private HashMap<Integer, Bet> bets = new HashMap<>();
	private int activeCoin;
	private final static String labelString = "Stan konta: ";
	private final int coinSize = 26;
	private Label money;
	private Text messageText;
	private Text resText;
	private Button[] outsideBets = new Button[6];
	private Button[] dozenBets = new Button[3];
	private Button[] columnBets = new Button[3];
	private Button zeroBet;
	/*
	 * 1%2 = 0 row
	 */
	private Button[][] straigh = new Button[3][12];
	private Button[][] splitHorizontal = new Button[2][12];
	private Button[] street = new Button[12];
	/*
	 * 1%2 != 0 row
	 */
	private Button[][] splitVertical = new Button[3][11];
	private Button[][] corner = new Button[2][11];
	private Button[] line = new Button[11];
	private BetFactory inside = new InsideBetFactory(),
			outside = new OutsideBetFactory(), dozen = new DozenBetFactory();

	private BetHandler straighHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.STRAIGHT, c);
		}
	};
	private BetHandler splitVerticalHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.SPLIT_VERTICAL, c);
		}
	};
	private BetHandler streetHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.STREET, c);
		}
	};
	private BetHandler splitHorizontalHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.SPLIT_HORIZONTAL, c);
		}
	};
	private BetHandler cornerHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.CORNER, c);
		}
	};
	private BetHandler lineHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			((InsideBetFactory) inside).setInitialnumber(number);
			return player.makeBet(inside, InsideBetFactory.SIX_LINE, c);
		}
	};
	private BetHandler dozenHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			return player.makeBet(dozen, number, c);
		}
	};
	private BetHandler outHandler = new BetHandler() {

		@Override
		public Bet placeBet(Credit c, int number) {
			return player.makeBet(outside, number, c);
		}
	};
	private Button readyButton;
	// private HashMap<Integer, Player> players;
	private TableView playerTable;
	private ListView<Integer> history;
	private ToggleButton btn200;
	private ToggleButton btn100;
	private ToggleButton btn50;
	private ToggleButton btn20;
	private ToggleButton btn10;
	private ToggleButton btn5;

	public Game(Player player, SceneHolder prevHolder) {
		this.player = player;
		this.previousHolder = prevHolder;
		sp = new StackPane();
		this.player.registerPlayerObserver(this);
		BorderPane mainPane = new BorderPane();
		ChatPanel chat = new ChatPanel(player);
		player.getServerHandler().registerObserver(chat);
		player.getServerHandler().registerObserver(this);
		VBox box = new VBox(spacing);
		history = createHistoryTable();
		playerTable = createPlayerTable();
		// playerTable.getItems().setAll(playermodelList);
		box.getChildren().setAll(playerTable, history);
		box.setPadding(new Insets(10,10,10,0));
		VBox chatAndTable = new VBox(spacing / 2);
		chatAndTable.setAlignment(Pos.CENTER);
		chatAndTable.setPadding(new Insets(10));

		chatAndTable.getChildren().setAll(createTable(), createGamePanel(),
				chat.getChat());
		mainPane.setLeft(chatAndTable);

		mainPane.setRight(box);
		mainPane.setId("main");
		mainPane.setOnKeyPressed(new EventHandler<KeyEvent>() {

			@Override
			public void handle(KeyEvent event) {
				if(event.getCode()==KeyCode.ESCAPE)
				if(!sp.getChildren().contains(menuBox))
				sp.getChildren().add(menuBox);
			}
		});
		menuBox = createMenuBox();
		roundBox = createRoundBox();
		sp.getChildren().setAll(mainPane);
		scene = new Scene(sp, rootWidth, rootHeigh);
		scene.getStylesheets().add("/table.css");

		ThreadManager.getInstance().execute(new Task() {

			@Override
			protected void task() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					Logger.getLogger(Game.class.getName()).log(Level.SEVERE,
							null, ex);
				}
				Game.this.player.getServerHandler().sendUpdatedPlayer(
						new PlayerFix(Game.this.player.getId(),
								Game.this.player.getCredits().getValue(),
								Game.this.player.getName()));
				stop();
			}
		});

	}
	private Node createRoundBox(){
		VBox box = new VBox(spacing);
		box.setMaxSize(400, 500);
		box.setId("menubox");
		box.setAlignment(Pos.CENTER);
		Image img = new Image(Game.class.getResourceAsStream("/wheelBack.png"));
		ImageView iv = new ImageView();
		iv.setImage(img);
		iv.setFitHeight(180);
		iv.setPreserveRatio(true);
		iv.setSmooth(true);
		messageText = new Text();
		messageText.setFont(Font.font("Rockwell Condensed", FontWeight.NORMAL, 18));
		resText = new Text();
		resText.setFont(Font.font("Rockwell Condensed", FontWeight.NORMAL, 60));
		resText.setFill(Color.YELLOW);
		resText.setCache(true);
		Reflection r = new Reflection();
		r.setTopOffset(-30);
        r.setFraction(0.9);
        resText.setEffect(r);
        //resText.setTranslateY(100);
		Button ok = new Button("Ok");
		ok.setId("game-button");
		ok.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				sp.getChildren().remove(roundBox);
				resText.setText("");
			}
		});
		box.getChildren().setAll(iv,messageText,resText,ok);
		return box;
	}
	private Node createMenuBox() {
		VBox box = new VBox(spacing);
		box.setMaxSize(300, 300);
		box.setId("menubox");
		Button exit,leave,back;
		exit = new Button("Wyjdź z Gry");
		exit.setId("game-button");
		leave =new Button("Opuść stół");
		leave.setId("game-button");
		back= new Button("Powrót");
		back.setId("game-button");
		exit.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				ThreadManager.getInstance().stopAll();
				System.exit(0);
				
			}
		});
		leave.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				ThreadManager.getInstance().stopAll();
				nextScene = previousHolder.getScene();
				for(SceneObserver ob:observers){
					ob.updateScene(nextScene);
				}
			}
		});
		
		back.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
			sp.getChildren().remove(menuBox);	
				
			}
		});
		box.getChildren().setAll(exit,leave,back);
		HelpButton helpButton = new HelpButton();
    	AnchorPane anchor = new AnchorPane();
    	AnchorPane.setBottomAnchor(helpButton, 0.0);
    	AnchorPane.setRightAnchor(helpButton, 10.0);
    	anchor.getChildren().setAll(helpButton);
    	anchor.maxHeight(300);
    	anchor.maxWidth(300);
    	anchor.setPadding(new Insets(20, 0, 0, 0));
    	box.getChildren().setAll(exit,leave,back,anchor);
        //BorderPane border = new BorderPane();
        //border.setCenter(box);
        //border.setBottom(anchor);
        //border.maxHeight(300);
        //border.maxWidth(300);
		return box;
	}

	private TableView createPlayerTable() {
		TableView tv = new TableView();
		TableColumn ids = new TableColumn("Lp.");
		ids.setPrefWidth(25);
		ids.setCellValueFactory(new PropertyValueFactory("id"));
		TableColumn players = new TableColumn("Gracz");
		players.setPrefWidth(100);
		players.setCellValueFactory(new PropertyValueFactory("name"));
		TableColumn gold = new TableColumn("Saldo");
		gold.setMaxWidth(60);
		gold.setCellValueFactory(new PropertyValueFactory("credit"));
		TableColumn action = new TableColumn("Status");
		action.setMaxWidth(150);
		action.setCellValueFactory(new PropertyValueFactory("action"));
		tv.getColumns().setAll(ids, players, gold, action);
		tv.getItems().setAll(playersData.values());
		return tv;
	}

	private ListView createHistoryTable() {
		ListView<Integer> lv = new ListView<>();
		lv.setCellFactory(new Callback<ListView<Integer>, ListCell<Integer>>() {

			@Override
			public ListCell<Integer> call(ListView<Integer> arg0) {
				return new HistoryCell();
			}
		});
		return lv;
	}


	private Node createTable() {
		BorderPane border = new BorderPane();
		border.setMaxSize(987, 276);
		border.setMinSize(987, 276);
		border.setPrefSize(987, 276);
		VBox root = new VBox(5);
		root.setAlignment(Pos.TOP_CENTER);
		VBox vb = new VBox(0);

		vb.setPadding(new Insets(1));
		for (int j = 0; j < 7; ++j) {
			HBox box = new HBox(8);

			box.setPadding(new Insets(0, 0, 0, 38));
			if (j == 0) {
				box.setSpacing(16 + coinSize);
				int index = 0;
				for (int i = 0; i < street.length; ++i) {
					street[i] = createButton(1 + index * 3);
					street[i].setOnAction(streetHandler);

					index++;
				}
				box.getChildren().setAll(street);
			} else if (j > 0 && j < 6) {
				int straighIndex = 0;
				int splitVIndex = 0;
				int splitHindex = 0;
				int cornerIndex = 0;
				for (int i = 0; i < 23; ++i) {
					int in = j / 2;

					if (i % 2 == 0) {

						if (j % 2 == 1) {

							straigh[in][straighIndex] = createButton(3 - in + 3
									* straighIndex);
							straigh[in][straighIndex]
									.setOnAction(straighHandler);
							box.getChildren().add(straigh[in][straighIndex]);
							straighIndex++;
						} else {

							splitHorizontal[in - 1][splitHindex] = createButton(2
									- in - 1 + 3 * splitHindex);
							splitHorizontal[in - 1][splitHindex]
									.setOnAction(splitHorizontalHandler);
							box.getChildren().add(
									splitHorizontal[in - 1][splitHindex]);
							splitHindex++;
						}
					} else {
						if (j % 2 == 1) {
							splitVertical[in][splitVIndex] = createButton(3
									- in + 3 * splitVIndex);
							splitVertical[in][splitVIndex]
									.setOnAction(splitVerticalHandler);
							box.getChildren().add(
									splitVertical[in][splitVIndex]);
							splitVIndex++;
						} else {
							corner[in - 1][cornerIndex] = createButton(2 - in
									- 1 * cornerIndex);
							corner[in - 1][cornerIndex]
									.setOnAction(cornerHandler);
							box.getChildren().add(corner[in - 1][cornerIndex]);
							cornerIndex++;
						}
					}
				}

			} else if (j == 6) {
				int index = 0;
				box.setSpacing(16 + coinSize);
				box.setPadding(new Insets(0, 0, 0, 38 + coinSize + 8));
				for (int i = 0; i < line.length; ++i) {

					line[i] = createButton(1 + index * 3);
					line[i].setOnAction(lineHandler);

					index++;
				}
				box.getChildren().setAll(line);
			}

			vb.getChildren().add(box);
		}
		root.getChildren().setAll(vb);
		VBox left = new VBox();
		left.setAlignment(Pos.CENTER);
		left.setPadding(new Insets(0, 0, 0, 41));
		zeroBet = createButton(0);
		zeroBet.setOnAction(straighHandler);
		left.getChildren().setAll(zeroBet);

		VBox right = new VBox(30);
		right.setAlignment(Pos.CENTER);
		columnBets[0] = createButton(DozenBetFactory.THIRD_COLUMN);
		columnBets[2] = createButton(DozenBetFactory.SECOND_COLUMN);
		columnBets[1] = createButton(DozenBetFactory.FIRST_COLUMN);
		for (Button b : columnBets) {
			b.setOnAction(dozenHandler);
		}
		right.getChildren().setAll(columnBets);
		right.setPadding(new Insets(0, 40, 0, 0));

		VBox bottom = new VBox(30);
		bottom.setAlignment(Pos.TOP_CENTER);
		HBox dozens = new HBox(255);
		dozenBets[0] = createButton(DozenBetFactory.FIRST_DOZEN);
		dozenBets[1] = createButton(DozenBetFactory.SECOND_DOZEN);
		dozenBets[2] = createButton(DozenBetFactory.THIRD_DOZEN);
		for (Button b : dozenBets) {
			b.setOnAction(dozenHandler);
		}
		dozens.getChildren().setAll(dozenBets);
		dozens.setAlignment(Pos.TOP_CENTER);
		HBox outters = new HBox(120);
		outters.setAlignment(Pos.TOP_CENTER);
		outters.setPadding(new Insets(0, 0, 20, 0));

		outsideBets[0] = createButton(OutsideBetFactory.FIRSTHALF);
		outsideBets[1] = createButton(OutsideBetFactory.EVEN);
		outsideBets[2] = createButton(OutsideBetFactory.RED);
		outsideBets[3] = createButton(OutsideBetFactory.BLACK);
		outsideBets[4] = createButton(OutsideBetFactory.ODD);
		outsideBets[5] = createButton(OutsideBetFactory.SECONDHALF);
		for (Button b : outsideBets) {
			b.setOnAction(outHandler);
		}

		outters.getChildren().setAll(outsideBets);

		bottom.getChildren().setAll(dozens, outters);
		border.setCenter(root);
		border.setLeft(left);
		border.setRight(right);
		border.setBottom(bottom);
		border.setId("root");
		return border;
	}

	private Button createButton(int number) {
		Button btn = new Button();
		TableBet tb = new TableBet();
		tb.setNumber(number);
		btn.setUserData(tb);
		btn.setMaxSize(coinSize, coinSize);
		btn.setMinSize(coinSize, coinSize);
		btn.setPrefSize(coinSize, coinSize);
		btn.setId("bet");
		return btn;
	}

	private Node createCoin(int value, int s) {
		StackPane sp = new StackPane();
		if (s == 0) {
			Circle c = new Circle(
					20,
					LinearGradient
							.valueOf("from 0% 20% to 100% 100%, #E8E833  0% , #F7FAA0 50%,  #D6D636 100%"));

			Label lbl = new Label(Integer.toString(value));
			lbl.setFont(Font.font("Rockwell Condensed", FontWeight.NORMAL, 18));
			sp.getChildren().setAll(c, lbl);
		} else if (s == 1) {
			Circle c = new Circle(
					coinSize / 2,
					LinearGradient
							.valueOf("from 0% 20% to 100% 100%, #E8E833  0% , #F7FAA0 50%,  #D6D636 100%"));

			Label lbl = new Label(Integer.toString(value));
			lbl.setFont(Font.font("Rockwell Condensed", FontWeight.NORMAL, 15));
			sp.getChildren().setAll(c, lbl);
		}

		return sp;
	}

	private Node createGamePanel() {
		ToggleGroup grp = new ToggleGroup();
		btn200 = createToggleButton(200);
		btn100 = createToggleButton(100);
		btn50 = createToggleButton(50);
		btn20 = createToggleButton(20);
		btn10 = createToggleButton(10);
		btn5 = createToggleButton(5);

		grp.getToggles().setAll(btn200, btn100, btn50, btn20, btn10, btn5);
		HBox hb = new HBox(20);

		grp.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {

			@Override
			public void changed(ObservableValue<? extends Toggle> val,
					Toggle oldTog, Toggle newTog) {
				if (newTog != null) {
					Game.this.activeCoin = (int) newTog.getUserData();
				}
			}
		});

		hb.setAlignment(Pos.CENTER);
		money = new Label(labelString + player.getCredits().getValue());

		money.setFont(Font.font("Bernard MT Condensed", FontWeight.NORMAL, 32));
		Label dollar = new Label("$");
		dollar.setFont(Font.font("Bernard MT Condensed", FontWeight.NORMAL, 32));
		HBox h = new HBox(10);
		h.getChildren().setAll(money, dollar);
		readyButton = new Button("Gotowe!");
		readyButton.setId("game-button");
		readyButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent arg0) {
				player.finishRound();
				messageText.setText(waitingString);
				sp.getChildren().add(roundBox);
			}
		});
		VBox rdyBox = new VBox();
		rdyBox.getChildren().setAll(readyButton);
		rdyBox.setAlignment(Pos.CENTER);
		;
		rdyBox.setPadding(new Insets(0, spacing, 0, spacing));
		hb.getChildren().setAll(h, rdyBox, btn200, btn100, btn50, btn20, btn10,
				btn5);
		HBox.setHgrow(h, Priority.ALWAYS);
		return hb;

	}

	private ToggleButton createToggleButton(int value) {
		ToggleButton btn = new ToggleButton();
		btn.setMaxSize(40, 40);
		btn.setMinSize(40, 40);
		btn.setPrefSize(40, 40);
		btn.setGraphic(createCoin(value, 0));
		btn.setId("coin");
		btn.setUserData(value);
		return btn;
	}

	private void clearButton(Button b) {
		if (b != null) {
			Object o = b.getUserData();
			TableBet tb = ((TableBet) o);
			if (tb != null) {
				tb.setMoney(0);
			}
			b.setGraphic(null);
		}
	}

	@Override
	public void updatePlayer(Player player) {
		// throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void updatePlayers(HashMap<Integer, Player> playerlist) {
		final ArrayList<PlayerDataModel> list = new ArrayList<>();
		Set set = playerlist.entrySet();
		Iterator i = set.iterator();
		while (i.hasNext()) {
			Map.Entry<Integer, Player> entry = (Map.Entry) i.next();
			String name = entry.getValue().getName();
			int coins = entry.getValue().getCredits().getValue();
			int id = entry.getKey();
			PlayerDataModel pdm = new PlayerDataModel(name, id, coins);
			list.add(pdm);
		}
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				playerTable.getItems().setAll(list);
			}
		});

	}

	@Override
	public void updateResult(Integer result) {
		final int res = result;
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				messageText.setText(roundDone);
				resText.setText(Integer.toString(res));
				history.getItems().add(res);
				history.getSelectionModel().selectLast();
				history.scrollTo(history.getSelectionModel().getSelectedIndex());
				history.getSelectionModel().clearSelection();
				for (Button[] s : straigh) {
					for (Button b : s) {
						clearButton(b);
					}
				}

				for (Button[] s : splitVertical) {
					for (Button b : s) {
						clearButton(b);
					}
				}

				for (Button[] s : corner) {
					for (Button b : s) {
						clearButton(b);
					}
				}
				for (Button[] s : splitHorizontal) {
					for (Button b : s) {
						clearButton(b);
					}
				}
				for (Button b : columnBets) {
					clearButton(b);
				}
				for (Button b : dozenBets) {
					clearButton(b);
				}
				for (Button b : line) {
					clearButton(b);
				}
				for (Button b : outsideBets) {
					clearButton(b);
				}
				for (Button b : street) {
					clearButton(b);
				}
				clearButton(zeroBet);
				//btn5.setDisable(false);btn10.setDisable(false);btn20.setDisable(false);btn50.setDisable(false);
				//btn100.setDisable(false);btn200.setDisable(false);
			}
		});
	}

	@Override
	public void updateReadyNotification(Integer playerId) {
	}

	@Override
	public void updateMessage(Message msg) {
	}

	@Override
	public void updateGameStarting() {
	}

	@Override
	public void updateGameOver() {
		Platform.runLater(new Runnable() {
			
			@Override
			public void run() {
				VBox box = new VBox(30);
				box.setId("gameoverbox");
				box.setMaxSize(400, 400);
				Image img; 
				Text text = new Text();
				text.setFont(Font.font("Rockwell Condensed", FontWeight.NORMAL, 40));
				text.setFill(Color.YELLOW);
				text.setCache(true);
				Reflection r = new Reflection();
				r.setTopOffset(-30);
		        r.setFraction(0.9);
		        text.setEffect(r);
		        if(player.getCredits().getValue() <= 0 ){
		        	text.setText("Jesteś spłukany!");
		        	img = new Image(Game.class.getResourceAsStream("/no_money.png"));
		        }else{
		        	text.setText("Wszyscy przeciwnicy zostali pokonani Gratulacje!!!");
		        	img = new Image(Game.class.getResourceAsStream("/coins.png"));
		        }
		        Button btn = new Button("Wyjdź z gry");
		        btn.setId("game-button");
		        btn.setOnAction(new EventHandler<ActionEvent>() {
					
					@Override
					public void handle(ActionEvent event) {
						nextScene = previousHolder.getScene();
						notifyObservers();
					}
				});
		        ImageView iv = new ImageView(img);
		        iv.setFitHeight(180);
		        iv.setSmooth(true);
		        box.getChildren().setAll(iv,text,btn);
		        sp.getChildren().add(box);
			}
		});
		
		
	}

	@Override
	public void reUpdatePlayer(PlayerFix player) {
		if(player == null){
			return;
		}
		final int id = player.getId();
		final int credit = player.getValue();

		//System.out.println("Credit = " + credit);
		final String name = player.getName();

		if (playersData.containsKey(id)) {
			playersData.get(id).setCredit(credit);
		} else {
			playersData.put(id, new PlayerDataModel(name, id, credit));
		}
		//System.out.println("PTD cred = " + playersData.get(id).getCredit());
		playermodelList.clear();
		for (PlayerDataModel pda : playersData.values()) {
			playermodelList.add(pda);
		}

		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				if (id == Game.this.player.getId()) {
					money.setText(labelString + credit);
				}
				playerTable.setItems(FXCollections
						.observableArrayList(playermodelList));

			}
		});
	}

	@Override
	public void updateRoundDoneNotification(Integer playerId) {
		final int id = playerId;
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				for (Iterator it = playerTable.getItems().iterator(); it
						.hasNext();) {
					PlayerDataModel pdm = (PlayerDataModel) it.next();
					if (pdm.getId() == id) {
						pdm.setAction("Oczekuje na pozostałych graczy");
					}
				}
			}
		});
	}

	private abstract class BetHandler implements EventHandler<ActionEvent> {

		@Override
		public void handle(ActionEvent ev) {
			if(activeCoin != 0){
			Button b = (Button) ev.getSource();
			TableBet tb = (TableBet) (b.getUserData());
			Credit c = new Credit();
			tb.setMoney(tb.getMoney() + activeCoin);
			b.setGraphic(createCoin(tb.getMoney(), 1));
			c.setValue(tb.getMoney());
			Bet bet = placeBet(c, tb.getNumber());
			if (bets.containsKey(tb.getId())) {
				Bet forCancel = bets.get(tb.getId());
				player.cancelBet(forCancel);

			}
			bets.put(tb.getId(), bet);
			}
		}

		public abstract Bet placeBet(Credit c, int number);
	}

	@Override
	public void updatePlayerCredits(int credits) {
		money.setText(labelString + credits);
		btn5.setDisable(false);btn10.setDisable(false);btn20.setDisable(false);btn50.setDisable(false);
		btn100.setDisable(false);btn200.setDisable(false);
		if(credits < 5){
			btn5.setDisable(true);
			activeCoin = 0;
		}
		if(credits < 10){
			
			btn10.setDisable(true);
			activeCoin = 0;
		}
		if(credits < 20){
			btn20.setDisable(true);
			activeCoin = 0;
		}
		if(credits < 50){
			btn50.setDisable(true);
			activeCoin = 0;
		}
		if(credits < 100){
			btn100.setDisable(true);
			activeCoin = 0;
		}
		if(credits<200){
			btn200.setDisable(true);
			activeCoin = 0;
		}
		
	}
	@Override
	public void updatePlayerLeft(Integer player) {
		
		
	}
}
